import { defineStore } from 'pinia'
import { reactive, computed, toRefs } from 'vue'
import { generate, getRgbStr } from '@arco-design/color'
import defaultSettings from '@/config/setting.json'

const storeSetup = () => {
  // App配置
  const settingConfig = reactive({ ...defaultSettings }) as App.SettingConfig
  // 全局撤回弹框
  const withdrawSecond = ref(0)
  // 全局撤回timer
  const withdrawTimer = ref(null)

  // 上一篇页面数据
  const lastPageData = reactive({
    aritcleId: '',
    editContet: '',
    articalTitleEdit: '',
  })
  // 页面切换动画类名
  const transitionName = computed(() => (settingConfig.animate ? settingConfig.animateMode : ''))

  // 深色菜单主题色变量
  const themeCSSVar = computed<Record<string, string>>(() => {
    const obj: Record<string, string> = {}
    const list = generate(settingConfig.themeColor, { list: true, dark: true })
    list.forEach((color: string, index: number) => {
      const rgbStr = getRgbStr(color)
      obj[`--primary-${index + 1}`] = rgbStr
    })
    return obj
  })

  // 设置上一篇内容
  const setLastPageData = (data: any) => {
    lastPageData.aritcleId = data.aritcleId
    lastPageData.editContet = data.editContet
    lastPageData.articalTitleEdit = data.articalTitleEdit
  }

  // 设置撤回秒
  const setWithdrawSecond = (second: number) => {
    withdrawSecond.value = second
  }
  // 设置timer
  const setwithdrawTimer = (timer: any) => {
    withdrawTimer.value = timer
  }

  // 切换主题 暗黑模式|简白模式
  const toggleTheme = (dark: boolean) => {
    if (dark) {
      settingConfig.theme = 'dark'
      document.body.setAttribute('arco-theme', 'dark')
    } else {
      settingConfig.theme = 'light'
      document.body.removeAttribute('arco-theme')
    }
    setThemeColor(settingConfig.themeColor)
  }

  // 设置主题色
  const setThemeColor = (color: string) => {
    if (!color) return
    settingConfig.themeColor = color
    const list = generate(settingConfig.themeColor, { list: true, dark: settingConfig.theme === 'dark' })
    list.forEach((color: string, index: number) => {
      const rgbStr = getRgbStr(color)
      document.body.style.setProperty(`--primary-${index + 1}`, rgbStr)
    })
  }

  // 初始化主题
  const initTheme = () => {
    if (!settingConfig.themeColor) return
    setThemeColor(settingConfig.themeColor)
  }

  // 设置左侧菜单折叠状态
  const setMenuCollapse = (collapsed: boolean) => {
    settingConfig.menuCollapse = collapsed
  }

  return {
    ...toRefs(settingConfig),
    transitionName,
    themeCSSVar,
    withdrawSecond,
    withdrawTimer,
    lastPageData,
    toggleTheme,
    setThemeColor,
    initTheme,
    setMenuCollapse,
    setWithdrawSecond,
    setwithdrawTimer,
    setLastPageData
  }
}

export const useAppStore = defineStore('app', storeSetup, { persist: true })
